package com.xintonghua.bussiness.ui.fragment.client.search;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.xintonghua.bussiness.BuildConfig;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.adapter.FriendAdapter;
import com.xintonghua.bussiness.api.HttpCent;
import com.xintonghua.bussiness.api.myinterface.MyUserList;
import com.xintonghua.bussiness.base.BaseActivity;
import com.xintonghua.bussiness.bean.Contant;
import com.xintonghua.bussiness.bean.MyMemberBean;
import com.xintonghua.bussiness.ui.CustomerActivity;
import com.xintonghua.bussiness.util.JsonUtil;
import com.xintonghua.bussiness.util.JumpUtils;
import com.xintonghua.bussiness.util.MyState;
import com.xintonghua.bussiness.util.PingYinHelper;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者：wanxianyi
 * 时间：2018/4/1.
 * 包名：com.xintonghua.bussiness.ui.fragment.client.search
 */

public class SearchResultActivity extends BaseActivity implements MyUserList {
    String keyword = "";
    @BindView(R.id.lv_user)
    ListView lvUser;
    private PinyinComparator pinyinComparator;

    FriendAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        ButterKnife.bind(this);
        onSimpleActionBar();
        setSimpleActionBar("搜索结果");
        keyword = getIntent().getStringExtra(BuildConfig.FLAVOR);
        initUI();
    }

    @Override
    public void initUI() {
        super.initUI();
        pinyinComparator = new PinyinComparator();
        List<Contant> contantList = new ArrayList<>();
        List<Contant> friends = setData();
        Collections.sort(friends, pinyinComparator);
        contantList.addAll(friends);
        adapter = new FriendAdapter(this, contantList);
        lvUser.setAdapter(adapter);
        lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                JumpUtils.jumpto(SearchResultActivity.this, CustomerActivity.class, (Serializable) adapter.getItem(i));
            }
        });
        adapter.notifyDataSetChanged();
        getList();

    }

    @Override
    public void dataBack(Object data, int order) {
        super.dataBack(data, order);
        switch (order) {
            case MyState.requestL3000:
                try {
                    List<MyMemberBean> list = (List<MyMemberBean>) JsonUtil.getListByJsonString(data.toString(), MyMemberBean.class);
                    List<Contant> contantList = new ArrayList<>();
                    List<Contant> friends = setData(list);
                    Collections.sort(friends, pinyinComparator);
                    contantList.addAll(friends);
//                    FriendAdapter adapter = new FriendAdapter(getActivity(), contantList);
                    adapter.setList(contantList);
                    adapter.notifyDataSetChanged();


                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void getList() {
        httpCent.getMyUserList(keyword, this, MyState.requestL3000);

    }

    @Override
    public List<Contant> MyUserBeanArrayToContantArray(List<MyMemberBean> MyUserlistBean) {

        List<Contant> contlist = new ArrayList<>();
        for (int i = 0; i < MyUserlistBean.size(); i++) {
            Contant contant = new Contant(MyUserlistBean.get(i).getUsername());
            contant.setFirstPY(MyUserlistBean.get(i).getFirstPY());
            contant.setNickname(MyUserlistBean.get(i).getNickname());
            contant.setPhone(MyUserlistBean.get(i).getPhone());
            contant.setId(MyUserlistBean.get(i).getId());
            contlist.add(contant);
        }


        return contlist;
    }

    private List<Contant> setData() {
        List<Contant> mContantList = new ArrayList<>();
        List<Contant> friends = new ArrayList<>();
        for (int i = 0; i < mContantList.size(); i++) {
            String pinyin;
            Contant friend = mContantList.get(i);
            pinyin = PingYinHelper.getPingYin(friend.getNickname());
            String letter = pinyin.substring(0, 1).toUpperCase();
            if (letter.matches("[A-Z]")) {
                friend.setPinYinName(letter);
            } else {
                friend.setPinYinName("#");
            }
            friends.add(friend);
        }
        return friends;
    }

    private List<Contant> setData(List<MyMemberBean> list) {
        List<Contant> mContantList = new ArrayList<>();
        mContantList = MyUserBeanArrayToContantArray(list);
        List<Contant> friends = new ArrayList<>();
        for (int i = 0; i < mContantList.size(); i++) {
            String pinyin;
            Contant friend = mContantList.get(i);
            pinyin = PingYinHelper.getPingYin(friend.getNickname());
            String letter = pinyin.substring(0, 1).toUpperCase();
            if (letter.matches("[A-Z]")) {
                friend.setPinYinName(letter);
            } else {
                friend.setPinYinName("#");
            }
            friends.add(friend);
        }
        return friends;
    }

    /**
     * 拼音首字母排序
     */
    public class PinyinComparator implements Comparator<Contant> {
        public int compare(Contant o1, Contant o2) {
            String str1 = getPingYin(o1.getNickname());
            String str2 = getPingYin(o2.getNickname());
            int flag = str1.compareTo(str2);
            return flag;
        }

        /**
         * 将字符串中的中文转化为拼音,其他字符不变
         *
         * @param inputString
         * @return
         */
        private String getPingYin(String inputString) {
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            format.setVCharType(HanyuPinyinVCharType.WITH_V);

            char[] input = inputString.trim().toCharArray();// 把字符串转化成字符数组
            String output = "";

            try {
                for (int i = 0; i < input.length; i++) {
                    // \\u4E00是unicode编码，判断是不是中文
                    if (java.lang.Character.toString(input[i]).matches(
                            "[\\u4E00-\\u9FA5]+")) {
                        // 将汉语拼音的全拼存到temp数组
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(
                                input[i], format);
                        // 取拼音的第一个读音
                        output += temp[0];
                    }
                    // 大写字母转化成小写字母
                    else if (input[i] > 'A' && input[i] < 'Z') {
                        output += java.lang.Character.toString(input[i]);
                        output = output.toLowerCase();
                    }
                    output += java.lang.Character.toString(input[i]);
                }
            } catch (Exception e) {
            }
            return output;
        }
    }

}

